package com.wyk.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyk.admin.common.biz.user.UserContext;
import com.wyk.admin.common.constant.RedisCacheConstant;
import com.wyk.admin.common.convention.exception.ClientException;
import com.wyk.admin.common.enums.UserErrorCodeEnum;
import com.wyk.admin.dao.entity.UserDO;
import com.wyk.admin.dao.mapper.UserMapper;
import com.wyk.admin.dto.req.UserLoginReqDTO;
import com.wyk.admin.dto.req.UserRegisterDTO;
import com.wyk.admin.dto.req.UserUpdateReqDTO;
import com.wyk.admin.dto.resp.UserLoginRespDTO;
import com.wyk.admin.dto.resp.UserRespDTO;
import com.wyk.admin.service.GroupService;
import com.wyk.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.wyk.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.wyk.admin.common.enums.UserErrorCodeEnum.USER_NAME_EXIST;


/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;
    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    @Override
    public UserRespDTO getUserByUsername(String username) {
        UserDO userDO = baseMapper.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username));
        if(userDO == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtil.copyProperties(userDO,userRespDTO);
        return userRespDTO;
    }

    /**
     * 查看用户名是否存在
     * @param usernmae  用户名
     * @return
     */
    @Override
    public Boolean hasUsername(String usernmae) {
        return !userRegisterCachePenetrationBloomFilter.contains(usernmae);
    }

    /**
     * 注册用户
     * @param requestParam
     */
    @Override
    public void register(UserRegisterDTO requestParam) {
        if (!hasUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if (!lock.tryLock()) {
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            if (insert < 1) {
                throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
            }
            userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
            groupService.saveGroup(requestParam.getUsername(), "默认分组");
        } catch (DuplicateKeyException ex) {
            throw new ClientException(USER_NAME_EXIST);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 修改用户
     * @param userUpdateDTO
     */
    @Override
    public void update(UserUpdateReqDTO userUpdateDTO) {
        if(!Objects.equals(userUpdateDTO.getUsername(), UserContext.getUsername())) {
            throw new ClientException("修改用户验证是否为登录用户!");
        }
        baseMapper.update(BeanUtil.toBean(userUpdateDTO, UserDO.class),
                Wrappers.lambdaUpdate(UserDO.class).eq(UserDO::getUsername,userUpdateDTO.getUsername()));
    }

    /**
     * 用户登录
     * @param userLoginReqDTO
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDO::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException("用户不存在");
        }
        Map<Object ,Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY  + userLoginReqDTO.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            stringRedisTemplate.expire(USER_LOGIN_KEY +userLoginReqDTO.getUsername(),30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        String uuid = UUID.randomUUID().toString();
        // stringRedisTemplate.opsForValue().set(uuid, JSONUtil.toJsonStr(userDO),300, TimeUnit.MINUTES);
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY +userLoginReqDTO.getUsername(),uuid, JSONUtil.toJsonStr(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY +userLoginReqDTO.getUsername(),30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    /**
     * 检查用户是否登录
     * @param username
     * @param token
     * @return
     */
    @Override
    public Boolean checkLogin(String username,String token) {
      return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY +username,token) != null;
    }

    /**
     * 退出登录
     * @param username
     * @param token
     */
    @Override
    public void logout(String username, String token) {
        if(checkLogin(username,token)) {
            stringRedisTemplate.delete(USER_LOGIN_KEY +username);
            return;
        }
        throw new ClientException("用户token不存在或者用户未登录");

    }
}
